var app = getApp();
Page({
  data: {
    dataLoaded: false,
    lng: '',
    lat: '',
    markers: [],
    controls: [],
    shopInfo: [],
    address: '',
    shopId:'',
    hasShop: false,
    currentStyle: false,
    userInfo:''
  },
  /**
  *分享
  */
  onShareAppMessage() {
    return {
      title: '爱在厦门,厦门在倾听',
      path: "/pages/index/index"
    }
  },
  /**
  *页面初始加载
  */
  onLoad(options) {
    wx.getStorage({
      key: 'userInfo',
      success: (res)=>{
       this.setData({
        userInfo:res.data
      })
       this._init();
     } 
   })
  },
  /**
  *检查是否授权地理位置
  */
  onShow() {
    this.checkLoc();
  },
  /**
  * 设置页面头部样式
  */
  onReady(){
   // app.setTitle();
 },
  /**
  *页面初始化
  */
  _init() {
    this._getLocation();
    wx.getSystemInfo({
      success:(res)=>{
        var winWid = res.windowWidth;
        var winHei = res.windowHeight;
        this.setData({
          controls: [
          {
            id: 1,
            iconPath: '/imgs/imgs_refurbish.png',
            position: {
              left: winWid-70,
              top: winHei - 180,
              width: 50,
              height: 50
            },
            clickable: true
          },
          {
            id: 2,
            iconPath: '/imgs/imgs_order_icon.png',
            position: {
             left: winWid - 70,
             top: winHei - 120,
             width: 50,
             height: 50
           },
           clickable: true
         },
         {
          id: 3,
          iconPath: '/imgs/imgs_center.png',
          position: {
            left: (winWid - 19) / 2,
            top: winHei / 2 - 33,
            width: 19,
            height: 33
          },
          clickable: false
        },
        ],
        dataLoaded: true
      });
      }
    });
  },
  /**
  *刷新
  */
  _refurbish() {
    this._getLocation();
    this.map();
  },
  /**
  * 操作地图控件
  */
  _controltap(evt) {
    var hasShop = this.data.hasShop;
    switch (evt.controlId) {
      case 1:
      this._refurbish();
      break;
      case 2:
      if (hasShop){
        wx.navigateTo({
          url:'/pages/order/index'
        })
      }
      break;
    }
  },

  /**
  * 点击页面气泡
  */
  _markertap(evt) {
    var shopInfo = this.data.shopInfo;
    shopInfo.some((item)=>{
      if (item.store_user_id === evt.markerId) {
        this.setData({
          address:item.address,
          shopId:item.store_user_id,
          currentStyle:true
        })
      }
      setTimeout(()=>{
       this.setData({
        currentStyle:false
      })
     },300)
    })
  },

  /**
  * 获取店铺列表
  */
  _getNearbyShop(location) {
    var url = 'Product/getProductList';
    var paramsData = {};
    app._post(url
      ,paramsData
      ,(res)=>{
        if (res.code === 1) {
          var shopInfo = res.data;
          var markers = [];
          if (shopInfo instanceof Array && shopInfo.length > 0){
            wx.setStorageSync('shopInfo',shopInfo);
            shopInfo.forEach((item)=> {
              var shopLat = item.Lat;
              var shopLng = item.Lng;
              item.juli = this.GetDistance(shopLat,shopLng,this.data.lat,this.data.lng);
              markers.push({
                id: item.store_user_id,
                latitude:shopLat,
                longitude: shopLng,
                addr: item.address,
                iconPath: "/imgs/imgs_dian.png",
                width: 36,
                height: 36
              });
              this._markers = markers;
            });
            this.setData({
              markers:this._markers,
              shopInfo,
              dataLoaded: true,
              hasShop:true,
              address:shopInfo[0].address,
              shopId:shopInfo[0].store_user_id
            });
          }
        }else{
          app.showError(result.msg);
        }
      })
  },
  /**
  *获取用户地理位置
  */
  _getLocation(){
   wx.getLocation({
    type: 'wgs84',
    success:(res)=>{
      var {
        latitude,
        longitude,
        speed,
        accuracy
      } = res;
      this.setData({
        lng:longitude,
        lat:latitude
      })
      this._getNearbyShop();
    },
    fail:(res)=>{
      this.checkLoc();
    }
  });
 },
  /**
   * 跳转页面
   */
   _jump(evt){
    var url = evt.currentTarget.dataset.url;
    wx.navigateTo({
      url
    })

  },
   /**
    *获取用户信息
    */
    _getUserInfo(evt) {
     var url = 'user/login';
     var paramsData = {
      user_info:evt.detail.rawData,
      encrypted_data: evt.detail.encryptedData,
      iv: evt.detail.iv,
      signature: evt.detail.signature
    }
    if (evt.detail.errMsg !== 'getUserInfo:ok') {
      return false;
    }

    wx.showLoading({ title: "正在登录", mask: true });
    // 执行微信登录
    wx.login({
      success: (res)=> {
        // 发送用户信息
        paramsData.code = res.code;
        app._post(url
          ,paramsData
          ,(result) => {
            if (result.code === 1) {
              // 记录token user_id
              this.setData({
                userInfo:evt.detail.userInfo || {}
              })
              wx.setStorageSync('token', result.data.token);
              wx.setStorageSync('user_id', result.data.user_id);
              wx.setStorage({
                key:'userInfo',
                data:evt.detail.userInfo
              })
              this._init();
            }else{
              app.showError(result.msg);
            }
          }
          , false
          , ()=>{
            wx.hideLoading();
          });
      }
    });
  },
  map(){
    this.mapCtx = wx.createMapContext('map');
    this.getCenterLocation();
    this.moveToLocation();
  },
  getCenterLocation(){
    this.mapCtx.getCenterLocation({
      success: (res)=>{}
    })
  },
  moveToLocation(){
    this.mapCtx.moveToLocation();
  },
  checkLoc(cb){
    wx.getSetting({
      success:(res)=>{
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            content:'地理位置授权失败，请重新授权',
            showCancel:false,
            success:()=>{
             wx.openSetting({
              success:()=> {
                this._getLocation();
              }
            });
           }
         })
        }
      }
    })
  },
  GetDistance(lat1,lng1,lat2,lng2){
    /*lat1,lng1为商铺的经纬度，lat2，lng2为当前定位的经纬度*/
    var a = (lat1 - lat2)* Math.PI /180.0;
    var  b = (lng1- lng2) * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
      Math.cos(lat1 *Math.PI / 180)*Math.cos(lat2 *Math.PI / 180)*Math.pow(Math.sin(b/2),2)));
      s = s *6378.137 ;// EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000; //输出为公里
      //s=s.toFixed(4);
      return s;
    }
  })